package xj.toolkit.test;

import io.netty.channel.ChannelHandlerContext;
import xj.toolkit.netty.handler.codec.http.HttpResponseHandler;
import xj.toolkit.util.Identifier;
import xj.toolkit.util.Identifyable;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.collections4.Closure;

public class RequestCallback extends HttpResponseHandler implements Closure<Identifyable<UUID>> {
	private static final Map<Identifier<?>, Identifyable<UUID>> responseMap = new HashMap<Identifier<?>, Identifyable<UUID>>();
	private static final Map<Identifier<?>, CountDownLatch> lockMap = new HashMap<Identifier<?>, CountDownLatch>();

	@Override
	public void execute(Identifyable<UUID> input) {
		Identifier<UUID> uuid = input.getIdentification();
		try {
			responseMap.put(uuid, input);
		} finally {
			lockMap.remove(uuid).countDown();
		}
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		@SuppressWarnings("unchecked")
		Identifyable<UUID> response = (Identifyable<UUID>) msg;
		execute(response);
	}

	@SuppressWarnings("unchecked")
	public <T extends Identifyable<?>> T getResponse(Identifier<?> uuid) {
		CountDownLatch lock = new CountDownLatch(1);
		lockMap.put(uuid, lock);
		try {
			lock.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return (T) responseMap.remove(uuid);
	}
}